package controller.servlets;

import com.fasterxml.jackson.databind.ObjectMapper;
import dao.AthleteCompetitionInformationDao;
import modle.AthleteCompetitionInformation;
import modle.ParamsUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serial;
import java.util.List;

@WebServlet(name = "SearchAthleteCompetitionInformationServlet", value = "/SearchAthleteCompetitionInformation")
public class SearchAthleteCompetitionInformationServlet extends HttpServlet {
    @Serial
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String ci_id = request.getParameter("ci_id");
        String athleteNo = request.getParameter("athleteNo");
        String status = request.getParameter("status");

        AthleteCompetitionInformationDao athleteCompetitionInformationDao = new AthleteCompetitionInformationDao();
        List<AthleteCompetitionInformation> dataList = athleteCompetitionInformationDao.getSearchAthleteCompetitionInformation(
                Integer.parseInt(ci_id),
                athleteNo,
                status);

        // 将Java对象转换为JSON字符串
        ObjectMapper mapper = new ObjectMapper();
//        String jsonString = mapper.writeValueAsString(dataList);
        String code = "{\"code\": 0, \"msg\": \"\", \"count\": " + dataList.size() + ", \"data\":";
        String jsonString = ParamsUtil.objectToJsonStr(dataList);
        // 设置响应的Content-Type并将JSON字符串写入输出流
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(code + jsonString + "}");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
